package com.leyou.order.service;

import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.holders.UserHolder;
import com.leyou.common.utils.BeanHelper;
import com.leyou.common.utils.IdWorker;
import com.leyou.item.client.ItemClient;
import com.leyou.item.dto.SkuDTO;
import com.leyou.order.dto.CartDTO;
import com.leyou.order.dto.OrderDTO;
import com.leyou.order.entity.Order;
import com.leyou.order.entity.OrderDetail;
import com.leyou.order.entity.OrderLogistics;
import com.leyou.order.enums.OrderStatusEnum;
import com.leyou.order.mapper.OrderDetailMapper;
import com.leyou.order.mapper.OrderLogisticsMapper;
import com.leyou.order.mapper.OrderMapper;
import com.leyou.order.utils.PayHelper;
import com.leyou.order.vo.OrderDetailVO;
import com.leyou.order.vo.OrderLogisticsVO;
import com.leyou.order.vo.OrderVO;
import com.leyou.user.UserClient;
import com.leyou.user.dto.AddressDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 虎哥
 */
@Slf4j
@Service
public class OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderDetailMapper detailMapper;

    @Autowired
    private OrderLogisticsMapper logisticsMapper;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private ItemClient itemClient;

    @Autowired
    private UserClient userClient;

    @Transactional
    public Long createOrder(OrderDTO orderDTO) {
        // 1.新增订单表
        Order order = new Order();
        // 1.1.订单id
        long orderId = idWorker.nextId();
        order.setOrderId(orderId);
        // 1.2.订单金额
        Map<Long, Integer> skuMap = orderDTO.getCarts().stream().collect(Collectors.toMap(CartDTO::getSkuId, CartDTO::getNum));
        // 1.2.1.获取商品id
        List<Long> idList = new ArrayList<>(skuMap.keySet());
        // 1.2.2.查询商品
        List<SkuDTO> skuDTOList = itemClient.querySkuByIds(idList);
        // 1.2.3.创建detail的集合，组织数据
        List<OrderDetail> detailList = new ArrayList<>();
        // 1.2.4.计算总价
        long total = 0L;
        for (SkuDTO sku : skuDTOList) {
            // 计算金额
            int num = skuMap.get(sku.getId());
            total += sku.getPrice() * num;
            // 创建orderDetail
            OrderDetail detail = new OrderDetail();
            detail.setTitle(sku.getTitle());
            detail.setSkuId(sku.getId());
            detail.setPrice(sku.getPrice());
            detail.setNum(num);
            detail.setOwnSpec(sku.getOwnSpec());
            detail.setImage(StringUtils.substringBefore(sku.getImages(), ","));
            detail.setOrderId(orderId);
            detailList.add(detail);
        }
        // 1.2.4.填写金额信息
        order.setTotalFee(total);
        order.setPostFee(0L);
        order.setActualFee(order.getTotalFee() + order.getPostFee());
        order.setPaymentType(orderDTO.getPaymentType());

        // 1.3.用户信息
        Long userId = UserHolder.getUser().getId();
        order.setUserId(userId);

        // 1.4.订单状态及时间
        order.setStatus(OrderStatusEnum.INIT.value());

        // 1.5.写入数据库
        orderMapper.insertSelective(order);

        // 2.新增订单详情表
        detailMapper.insertList(detailList);

        // 3.新增订单物流表
        // 3.1.获取id
        Long id = orderDTO.getAddressId();
        // 3.2.根据id查询物流地址
        AddressDTO address = userClient.queryAddressById(userId, id);
        // 3.3.封装到OrderLogistics对象
        OrderLogistics logistics = BeanHelper.copyProperties(address, OrderLogistics.class);
        logistics.setOrderId(orderId);
        // 3.4.写入数据库
        logisticsMapper.insertSelective(logistics);

        // 4.减库存
        try {
            itemClient.minusStock(skuMap);
        } catch (Exception e) {
            throw new LyException(ExceptionEnum.STOCK_NOT_ENOUGH);
        }

        // TODO 扣减优惠券

        // TODO 删除购物车

        // 5.返回订单编号
        return orderId;
    }

    public OrderVO queryOrderById(Long orderId) {
        // 查询订单
        Order order = orderMapper.selectByPrimaryKey(orderId);
        if (order == null) {
            throw new LyException(ExceptionEnum.ORDER_NOT_FOUND);
        }
        OrderVO orderVO = BeanHelper.copyProperties(order, OrderVO.class);

        // 封装orderDetail
        orderVO.setDetailList(queryDetailByOrderId(orderId));
        // 封装orderLogistics
        orderVO.setLogistics(queryLogisticsByOrderId(orderId));
        return orderVO;
    }

    private OrderLogisticsVO queryLogisticsByOrderId(Long orderId) {
        OrderLogistics logistics = logisticsMapper.selectByPrimaryKey(orderId);
        if (logistics == null) {
            throw new LyException(ExceptionEnum.ORDER_NOT_FOUND);
        }
        return BeanHelper.copyProperties(logistics, OrderLogisticsVO.class);
    }

    private List<OrderDetailVO> queryDetailByOrderId(Long orderId) {
        OrderDetail record = new OrderDetail();
        record.setOrderId(orderId);
        List<OrderDetail> list = detailMapper.select(record);
        if (CollectionUtils.isEmpty(list)) {
            throw new LyException(ExceptionEnum.ORDER_NOT_FOUND);
        }
        return BeanHelper.copyWithCollection(list, OrderDetailVO.class);
    }

    @Autowired
    private PayHelper payHelper;

    public String queryPayUrl(Long orderId) {
        // 根据id查询订单
        Order order = orderMapper.selectByPrimaryKey(orderId);
        if (order == null) {
            throw new LyException(ExceptionEnum.ORDER_NOT_FOUND);
        }
        // 判断订单状态
        if(!Objects.equals(order.getStatus(), OrderStatusEnum.INIT.value())){
            // 订单已经支付
            throw new LyException(ExceptionEnum.INVALID_ORDER_STATUS);
        }
        // TODO 商品描述
        return payHelper.unifiedOrder("乐优商城商品", orderId, order.getActualFee());
    }

    public Map<String, String> handleNotify(Map<String, String> data) {
        try {
            Map<String,String> result = new HashMap<>();
            result.put("return_code", "SUCCESS");
            result.put("return_msg", "OK");
            // 1.签名校验
            payHelper.checkSignature(data);

            // 2.金额校验
            // 2.1.获取订单编号和金额
            String out_trade_no = data.get("out_trade_no");
            String total_fee = data.get("total_fee");
            if(StringUtils.isBlank(out_trade_no) || StringUtils.isBlank(total_fee)){
                throw new RuntimeException("数据有误，订单编号或金额为空！");
            }
            // 2.2.查询数据库中的订单
            Order order = orderMapper.selectByPrimaryKey(Long.valueOf(out_trade_no));
            // 2.3.比较金额
            if(!total_fee.equals(order.getActualFee().toString())){
                // 金额不匹配
                throw new RuntimeException("数据有误，订单金额不匹配！");
            }

            // 3.幂等校验
            if(!Objects.equals(order.getStatus(), OrderStatusEnum.INIT.value())){
                // 通知已经处理过了，属于从重复通知
                return result;
            }

            // 4.支付成功，修改订单状态
            Order record = new Order();
            record.setOrderId(order.getOrderId());
            record.setStatus(OrderStatusEnum.PAY_UP.value());
            record.setPayTime(new Date());
            int count = orderMapper.updateByPrimaryKeySelective(record);
            if(count != 1){
                throw new RuntimeException("更新订单状态失败！");
            }
            // 5.返回成功结果
            log.info("支付回调处理成功，订单编号:{}", order.getOrderId());
            return result;
        } catch (RuntimeException e) {
            log.error("回调处理失败，原因：{}", e.getMessage());
            throw new LyException(ExceptionEnum.INVALID_NOTIFY_PARAM);
        }
    }

    public Integer queryPayStatus(Long orderId) {
        Order order = orderMapper.selectByPrimaryKey(orderId);
        if(order == null){
            throw new LyException(ExceptionEnum.ORDER_NOT_FOUND);
        }
        return order.getStatus();
    }
}
